﻿using System;
using System.IO;
using System.Collections.Generic;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using CommDll;
using System.Management;
using System.Xml.Linq;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;


namespace InstitutionAssitant
{
    /// <summary>
    /// 系统处理类
    /// </summary>
    public class AppInfo
    {
        #region 000 调用系统api
        // 显示系统窗体
        [DllImport("User32.dll")]
        public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        public const int WS_SHOWNORMAL = 1;
        // 设置窗体到最前端
        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        // 取窗体线程
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        #endregion
        #region 001 自定义属性
        // 升级程序
        public static string m_strUpdaterFileName = string.Format("{0}\\{1}", System.Windows.Forms.Application.StartupPath, "AutoUpdater.exe");
        // 本系统App相关
        public static string m_strAppName = ""; // 程序名称
        public static string m_strCompany = ""; // 公司名称
        public static string m_strCopyright = ""; // 公司名称
        public static string m_strAppVer = "";  // 程序版本号
        public static Icon m_iconApp = null;    // 程序图标

        public static Boolean m_bAppState = false;    // 系统状态 false:初始化验证不通过 true：验证通过
        public static bool m_bLogin;    // 是否通过系统验证
        public static UserInfo m_UserInfo = new UserInfo();    // 用户信息 
        public static DataTable m_dtWarehouse;    // 仓库数据
        public static Color m_colorDgvCurrent = Color.LightSteelBlue; // dgv当前行底色
        #endregion
        static AppInfo(){
            // 取程序集相关信息
            Assembly asm = Assembly.GetExecutingAssembly();
            m_strAppName = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyTitleAttribute))).Title.ToString();
            m_strCopyright = ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCopyrightAttribute))).Copyright.ToString();
            m_strCompany = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCompanyAttribute))).Company.ToString();
            m_strAppVer = asm.GetName().Version.ToString();
            // 取图标信息
            m_iconApp = Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
        }
     
        /// <summary>
        /// 是否有相同实例在运行,第一次运行，返回null
        /// </summary>
        /// <param name="bIsShow">是否显示进程</param>
        /// <returns></returns>
        public static Process _runningInstance(Boolean bIsShow = true)
        {
            Process processCurrent = Process.GetCurrentProcess();
            Process[] processList = Process.GetProcessesByName(processCurrent.ProcessName);
            foreach (Process process in processList)
            {
                if (process.Id != processCurrent.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\").ToLower() == processCurrent.MainModule.FileName.ToLower())
                    {
                        // 是否要显示进程
                        if (bIsShow)
                        {
                            _handleRunningInstance(process);
                        }
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 显示正在运行的进程当前窗口
        /// </summary>
        /// <param name="instance"></param>
        public static void _handleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 1); //置窗口为正常状态
            SetForegroundWindow(instance.MainWindowHandle);
        }

        #region 001 相关数据处理方法
        /// <summary>
        /// 是否进行系统更新
        /// </summary>
        public static Boolean _isUpdate()
        {
            Boolean bResult = false;
            // 01 取需更新文件数以及相关配置文件是否合法
            bResult = (AppUpdater._checkForUpdate() > 0);
            if (bResult)
            {
                if (CommFun._messageBoxShow("系统检测到新版本，是否需要更新？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    bResult = true;
                }
                else
                {
                    bResult = false;
                }
            }
            // 02 更新
            if (bResult)
            {
                // 启动更新程序
                Process.Start(AppInfo.m_strUpdaterFileName);
                Environment.Exit(0);
                Application.ExitThread();
                Application.Exit();
            }
            return bResult;
        }
        #endregion

        #region 002 系统初始化方法
        /// <summary>
        /// 取系统Config.ini 信息
        /// </summary>
        public static void _getConfigInfo()
        {
            // 01 设置ini文件名
            AppConfig._readData();
        }

        /// <summary>
        /// 连接数据库
        /// 如果数据库连接不正常，弹出数据库设置窗体
        /// </summary>
        public static Boolean _connectDB()
        {
            Boolean bResult = false;
            DbHelper._initDb(); // 数据库初始化
            if (!DbHelper.DBAccess[0].m_bConnected)
            {
                DbHelper._connectDb();
            }
            bResult = DbHelper.DBAccess[0].m_bConnected;
            return bResult;
        }
        #endregion
    }
}